const {NetInfo, Platform} = require('react-native');

export class NetUtil {

    /**
     * 注册 网络状态监听
     * @param {Function} cb_network_state (network_state) => { ... }
     * @param {Function} cb_network_state_change (network_state) => { ... }
     */
    static registerNetworkStateListener = (cb_network_state = null, cb_network_state_change = null) => {
        NetInfo.getConnectionInfo().done((net_state) => {
            if (cb_network_state) {
                cb_network_state(net_state)
            }
            NetInfo.addEventListener('connectionChange',
                (net_state) => {
                    if (cb_network_state) {
                        cb_network_state(net_state)
                    }

                    if (cb_network_state_change) {
                        cb_network_state_change(net_state)
                    }
                }
            )
        });
    };

    /**
     * 网络是否连接
     * @param {none|wifi|cell|unknown} network_state
     * @return {boolean}
     */
    static isNetworkConnected = (network_state) => {
        if (!network_state)
            return false;

        let ns = network_state.toUpperCase();

        if (Platform.OS === 'ios') {
            if (ns == 'WIFI' ||
                ns == 'CELL')
                return true
        } else if (Platform.OS == 'android') {
            let no_network = {
                'NONE': 1,
                'UNKNOWN': 1,
                'BLUETOOTH': 1,
            };

            if (no_network[ns])
                return false;
            else
                return true
        }
        return false
    };
    /**
     * wifi是否连接
     * @param {none|wifi|cell|unknown} network_state
     * @return {boolean}
     */
    static isNetworkWifi = (network_state) => {
        if (!network_state)
            return false;

        let ns = network_state.toUpperCase();
        return ns == 'WIFI'
    };
    /**
     * 是否是基站连接 2g,3g,4g...
     * @enum {'none'|'wifi'|'cell'|'unknown'} network_state
     * @return {boolean}
     */
    static isNetworkCell = (network_state) => {
        if (!network_state)
            return false

        let ns = network_state.toUpperCase()

        if (Platform.OS === 'ios') {
            return ns == 'CELL'
        } else if (Platform.OS == 'android') {
            return ns.contains('MOBILE')
        }

        return false;
    }
}